<?php

namespace Portal\LessonBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Portal\LessonBundle\Entity\Lesson;
use Portal\LessonBundle\Form\LessonType;
use Portal\LessonBundle\Repository\LessonRepository;
use Portal\NotificationBundle\Entity\Notification;
use Portal\MainBundle\Utils\customFunctions;

class LessonController extends Controller
{

  private $activeContractStatus = "(1, 2, 3, 4, 5)";
  private $activeStatus = "('created', 'complete', 'userDenied', 'tutorDenied', 'adminDenied')";
  

  public function createAction(Request $request)
  {
    $user = $this->container->get('security.context')->getToken()->getUser();

    // CHECK USER
    if (!is_object($user) || $user == 'anon.') {
      $this->get('session')->setFlash('error', 'Та нэвтэрч орно уу.');
      return $this->redirect($this->generateUrl('homepage'));
    }

    $entity = new Lesson();
    $form = $this->createForm(new LessonType(), $entity);
    $form->bind($request);

    $messageId = $request->request->get('messageId');
    $message = $this->getDoctrine()->getEntityManager()->getRepository('PortalLessonBundle:Message')->find($messageId);

    // Check message isset
    if (!$message) {
      $this->get('session')->setFlash('error', 'Ийм мессеж байхгүй байна.');
      return $this->redirect($this->generateUrl('homepage'));
    }

    // Check Message for Lesson
    if ($this->checkUserForMessage($message, $user) == FALSE) {
      // Flash text нь function дотороо хийгдсэн байгаа
      return $this->redirect($this->generateUrl('homepage'));
    }

    // Get tutor
    $tutor = $this->getDoctrine()->getEntityManager()->getRepository('PortalLessonBundle:Tutor')->find($user->getId());

    // Get user
    $lessonUser = $this->findUserId($message);

    // Check users
    if (!$tutor || !$lessonUser) {
      $this->get('session')->setFlash('error', 'Энэ мессежээр хичээл үүсгэж болохгүй байна.Оролцогчид Хэрэглэгч, Эсвэл багш байх ёстой!');
      return $this->redirect($this->generateUrl('homepage'));
    }

    if ($form->isValid()) {

      $entity->setTutorFlag($this->container->getParameter('tutorFlagAgreed'));
      $entity->setCreatedAt(new \DateTime());
      $entity->setStatus($this->getDoctrine()->getEntityManager()->getRepository('PortalLessonBundle:LessonStatus')->find($this->container->getParameter('lessonCreate')));
      $entity->setTutor($tutor);
      $entity->setMessage($message);
      $entity->setUser($lessonUser);
      $entity->setIsActive($this->container->getParameter('statusActive'));
      $em = $this->getDoctrine()->getManager();
      $em->persist($entity);
      $em->flush();

      //$this->addNotification($entity->getId());
      $this->addNotificationToTutor($entity->getId());
      $this->get('session')->setFlash('notice', $this->container->getParameter('successSave'));
      return $this->redirect($this->generateUrl('homepage'));
    }

    $this->get('session')->setFlash('error', $this->container->getParameter('failSave'));
    return $this->redirect($this->generateUrl('homepage'));
  }

  public function showLessonAction($lessonId, $notificationId = null)
  {
    $user = $this->checkUser();
    
    $lesson = $this->getDoctrine()->getEntityManager()->getRepository('PortalLessonBundle:Lesson')->findOneBy(array('id' => $lessonId));

    if (!$lesson) {
      $this->get('session')->setFlash('error', 'Уучлаарай ийм хичээл байхгүй байна.');
      return $this->redirect($this->generateUrl('homepage'));
    }

    // Энэ хэрэглэгчид ирсэн  эсэхийг шалгаж байна
    if (in_array($this->container->getParameter('ROLE_USER'), $user->getRoles())) {
      if ($lesson->getUser()->getId() != $user->getId()) {
        $this->get('session')->setFlash('error', 'Уучлаарай энэ хичээл танд байхгүй байна.');
        return $this->redirect($this->generateUrl('homepage'));
      }
    } else if (in_array($this->container->getParameter('ROLE_TUTOR'), $user->getRoles())) {
      // Энэ багшид ирсэн  эсэхийг шалгаж байна    
      if ($lesson->getTutor()->getId() != $user->getId()) {
        $this->get('session')->setFlash('error', 'Уучлаарай энэ хичээл танд байхгүй байна.');
        return $this->redirect($this->generateUrl('homepage'));
      }
    } else {
      $this->get('session')->setFlash('error', 'Уучлаарай та нэвтэрч орно уу.');
      return $this->redirect($this->generateUrl('logout'));
    }

    if (isset($notificationId)) {      
      $this->showNotification($notificationId);
    }

    $contractId = $this->getDoctrine()->getEntityManager()->getRepository('PortalContractBundle:Contract')->checkActiveContractForLesson($lessonId, $this->activeStatus);
    
    return $this->render('PortalLessonBundle:Default:show.html.twig', array(
                'lesson' => $lesson,
                'lessonId' => $lessonId,
                'studentId' => $lesson->getUser()->getId(),
                'contract' => $contractId,
            ));
  }

  private function checkUser()
  {
    $user = $this->container->get('security.context')->getToken()->getUser();

    if ($user) {
      if (!is_object($user)) {
        header('Location: /logout');
        return;
      }

      if (is_array($user->getRoles()) == FALSE) {
        header('Location: /logout');
        return;
      }

      return $user;
    } else {
      header('Location: /logout');
      return;
    }
  }

  private function checkUserForMessage($message, $user)
  {
    $indicator = TRUE;
    if ($message->getReceiverId() == $user->getId() && in_array($message->getReceiverRole(), $user->getRoles()) == TRUE) {

      $lesson = $this->getDoctrine()->getEntityManager()->getRepository('PortalLessonBundle:Lesson')->findOneBy(array('message' => $message));
      $lessonStatus = $this->getDoctrine()->getEntityManager()->getRepository('PortalLessonBundle:LessonStatus')->find($this->container->getParameter('lessonStatusUserDenied'));
      
      if ($lesson) {
        
        $contractIsActive = $this->getDoctrine()->getEntityManager()->getRepository('PortalContractBundle:Contract')->findStatusByLessonId($lesson->getId());
        if($contractIsActive){
          if ($lesson->getStatus() == $lessonStatus && $contractIsActive == $this->container->getParameter('statusInActive')) {
            $indicator = TRUE;
          } else {            
            $this->get('session')->setFlash('error', 'Энэ мессежээр хичээлийн хуваарь үүсгэгдсэн байна.');
            $indicator = FALSE;
          }
        }else{
          $this->get('session')->setFlash('error', 'Энэ хичээлийн хуваарьтай холбогдсон гэрээ цуцлагдаагүй байна.');
          $indicator = FALSE;
        }
      }

      if ($indicator == TRUE) {
        return TRUE;
      } else {
        return FALSE;
      }
    } else {
      // Энэ мессеж нь уг хэрэглэгчид ирээгүй
      // эрх хүрэхгүй байна        
      $this->get('session')->setFlash('error', 'Алдаа гарлаа.');
      $indicator = FALSE;
    }
  }

  public function findUserId($message)
  {
    // Эхлээд sender user байгаа эсэхийг шалгана
    if ($message->getSenderRole() == $this->container->getParameter('ROLE_USER') && (int) $message->getSenderId() > 0) {
      $user = $this->getDoctrine()->getEntityManager()->getRepository('PortalLessonBundle:User')->find((int) $message->getSenderId());

      if ($user) {
        return $user;
      } else {
        return false;
      }
    } else {
      // sender Tutor байгаа эсэхийг шалгана
      if ($message->getSenderRole() == $this->container->getParameter('ROLE_TUTOR') && (int) $message->getSenderId() > 0) {
        $tutor = $this->getDoctrine()->getEntityManager()->getRepository('PortalLessonBundle:Tutor')->find((int) $message->getSenderId());
        if ($tutor) {
          return $tutor;
        } else {
          return false;
        }
      } else {
        return false;
      }
    }
  }

  public function showLessonByComponentAction($lessonId)
  {
    $lesson = $this->getDoctrine()->getEntityManager()->getRepository('PortalLessonBundle:Lesson')->findOneBy(array('id' => $lessonId));
    return $this->render('PortalLessonBundle:Default:showLessonByComponent.html.twig', array(
                'lesson' => $lesson,
                'lessonId' => $lessonId
            ));
  }

  private function addNotification($lessonId)
  {
    $user = $this->checkUser();
    
    $lesson = $this->getDoctrine()->getEntityManager()->getRepository('PortalLessonBundle:Lesson')->find($lessonId);


    $notificationType = $this->container->getParameter('notificationLesson');
    $tableId = $lessonId;
    $toUrl = $this->container->getParameter('notificationUrlLesson') . $lessonId;
    $description = 'Танд "" - с хичээлийн хуваарь ирлээ.';
    $tutorId = $lesson->getTutor()->getId();
    $userId = $lesson->getUser()->getId();
    $status = $this->container->getParameter('notificationStatusUnread');
    $isActive = $this->container->getParameter('statusActive');
    $createdAt = new \DateTime();
    // SET DIRECTION
    if (in_array($this->container->getParameter('ROLE_TUTOR'), $user->getRoles())) {
      $direction = $this->container->getParameter('ROLE_USER');
      $lastInsertedId = $this->saveNotification($notificationType, $tableId, $toUrl, $description, $tutorId, $userId, $status, $isActive, $createdAt, $direction);
    }else if (in_array($this->container->getParameter('ROLE_TUTOR'), $user->getRoles())) {
      $direction = $this->container->getParameter('ROLE_TUTOR');
      $lastInsertedId = $this->saveNotification($notificationType, $tableId, $toUrl, $description, $tutorId, $userId, $status, $isActive, $createdAt, null, $this->container->getParameter('ROLE_TUTOR'));
    }
    
    return $lastInsertedId;
  }
  
  
  private function addNotificationToTutor($lessonId)
  {
    $user = $this->checkUser();

    $lesson = $this->getDoctrine()->getEntityManager()->getRepository('PortalLessonBundle:Lesson')->find($lessonId);


    $notificationType = $this->container->getParameter('notificationLesson');
    $tableId = $lessonId;
    $toUrl = $this->container->getParameter('notificationUrlLesson') . $lessonId;
    $description = 'Танд тэрнээс хичээлийн хуваарь ирлээ.';
    $tutorId = $lesson->getTutor()->getId();
    $userId = $lesson->getUser()->getId();
    $status = $this->container->getParameter('notificationStatusUnread');
    $isActive = $this->container->getParameter('statusActive');
    $createdAt = new \DateTime();
    // SET DIRECTION    
    $direction = $this->container->getParameter('ROLE_TUTOR');
    $lastInsertedId = $this->saveNotification($notificationType, $tableId, $toUrl, $description, $tutorId, $userId, $status, $isActive, $createdAt, null, $this->container->getParameter('ROLE_TUTOR'));
    

    return $lastInsertedId;
  }

  /**
   * Notification хадгалах
   * 
   * @param type $noificationType
   * @param type $tableId
   * @param type $toUrl
   * @param type $description
   * @param type $tutorId
   * @param type $userId
   * @param type $status
   * @param type $isActive
   * @param type $createdAt
   */
  private function saveNotification($notificationType, $tableId, $toUrl, $description, $tutorId, $userId, $status, $isActive, $createdAt, $direction = null, $directionTutor = null)
  {
    $notification = new Notification();
    $notification->setNotificationType($notificationType);
    $notification->setTableId($tableId);
    $notification->setToUrl($toUrl);
    $notification->setDescription($description);
    $notification->setTutorId($tutorId);
    $notification->setUserId($userId);
    
    $notification->setIsActive($isActive);
    $notification->setCreatedAt($createdAt);
    $notification->setUpdatedAt(new \DateTime());
    
    if(isset($direction))
    {
      $notification->setUserShowPermission($direction);
      $notification->setStatus($status);
    }
    
    if(isset($directionTutor))
    {
      $notification->setTutorShowPermission($directionTutor);
      $notification->setStatusTutor($status);
    }
    
    $em = $this->getDoctrine()->getManager();
    $em->persist($notification);
    $em->flush();

    return $notification->getId();
  }

  private function showNotification($notificationId)
  {
    $notification = $this->getDoctrine()->getEntityManager()->getRepository('PortalNotificationBundle:Notification')->find($notificationId);
    if ($notification) {
      
      $user = $this->checkUser();
      
      if (in_array($this->container->getParameter('ROLE_USER'), $user->getRoles())) {
        $notification->setStatus($this->container->getParameter('notificationStatusRead'));
      } else if (in_array($this->container->getParameter('ROLE_TUTOR'), $user->getRoles())) {        
        $notification->setStatusTutor($this->container->getParameter('notificationStatusRead'));
      }


      // SAVE CONTRACT
      $em = $this->getDoctrine()->getManager();
      $em->persist($notification);
      $em->flush();


      return true;
    }
  }

}
